<template>
    <div>
        <!-- 第一层区域 -->
        <el-row>
            <el-col :span="12">
                <el-select v-model="param.classId" placeholder="请选择">
                    <el-option v-for="(item,index) in classes" :key="index" :label="item.className"
                        :value="item.id"></el-option>
                </el-select>
                &nbsp;&nbsp;
                <el-select v-model="param.workId" placeholder="请选择">
                    <el-option v-for="(item,index) in wakes" :key="index" :label="item.title"
                        :value="item.id"></el-option>
                </el-select>
            </el-col>
            <span v-if="endTimeFalt === 1">&nbsp;&nbsp;该试卷截止答题</span>
            <span v-if="!endTimeFalt === 0">&nbsp;&nbsp;该试卷还未截止答题</span>
            <span v-if="endTimeFalt != -1">&nbsp;&nbsp;结束时间: {{endTime}}</span>
        </el-row>

        <!-- 第二层区域 -->
        <div class="first">
            <!-- 题目展示区以及题目人员更改 -->
            <div class="first_first">
                <div class="question_view">
                    <el-input :readonly=true type="textarea" :rows="23" placeholder="学生答案展示区" v-model="code">
                    </el-input>
                </div>
                <div class="change">
                    <div>
                        <el-button @click="lastStudent()">上一个学生</el-button>
                        <el-button @click="lastQuestion()">上一题</el-button>
                    </div>
                    <div>
                        第{{workOrder}}题/{{workQuestionScore.length}}
                        <br>
                        第{{user.order + 1}}人/{{userIds.length}}
                    </div>
                    <div>
                        <el-button @click="nextQuestion()">下一题</el-button>
                        <el-button @click="nextStudent()">下一个学生</el-button>
                    </div>
                </div>

            </div>

            <!-- 学生信息区以及题目分值区 -->
            <div class="first_second">
                <span class="question_view_byOrder">{{workQuestionQuestion[workOrder-1]}}</span>&nbsp;
                <hr>
                <span>{{user.username}} </span>&nbsp;
                <span>{{user.StudentNumber}}</span>&nbsp;
                <span>得分：{{totalscores}}</span>
                <hr>

                <!-- 分数打分区 -->
                <div v-for="(item,index) in workStudentScore" :key="index">
                    <el-input placeholder="请输入分数" v-model="workStudentScore[index]" :readonly="flat">
                        <template slot="prepend">第{{index+1}}问
                        </template>
                        <template slot="append">{{workQuestionScore[index]}}</template>
                    </el-input>
                </div>
                <div>
                    <el-button @click="dialogVisible = true" v-if="!flat">提交打分</el-button>
                    <el-button @click="dialogVisible_update = true" v-if="!flat_update">提交修改打分</el-button>
                    <el-button @click="flat_update = false,flat = false" v-if="flat_update">修改分数</el-button>
                </div>
            </div>
        </div>

        <el-dialog title="提交分数" :visible.sync="dialogVisible" width="30%">
            <span>
                该学生的得分是：{{totalscores}}
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitStudentScore()">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog title="提交修改分数" :visible.sync="dialogVisible_update" width="30%">
            <span>
                该学生的得分是：{{totalscores}}
            </span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible_update = false">取 消</el-button>
                <el-button type="primary" @click="submitStudentScore_update()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>



<script>
    export default {
        computed: {
            totalscores() {
                let sc = 0
                for (let i = 0; i < this.workStudentScore.length; i++) {
                    sc = Number(this.workStudentScore[i]) + sc
                }

                return sc
            }
        },
        watch: {
            // 题目顺序
            'workOrder': {
                handler(newVal) {
                    this.getStudentAnswer(0)
                },
            },
            // 班级id
            'param.classId': { // 监视param对象中的classId属性变化  
                handler(newVal) {
                    // 清空作业表   一切归零
                    this.param.workId = null
                    this.endTime = null,
                    this.code = null,
                    this.wakes = null,
                    this.workQuestionScore = [],// 题目分数
                    this.workQuestionQuestion = [],// 题目信息
                    this.workStudentScore = [],


                    this.getWorks() // classid发生变化，这个班级的作业信息发生变化
                    this.getUserId() // 这个班级的用户信息id发生变化
                    if (this.param.workId != null) {
                        this.getEndTime()// 获取结束时间
                    }
                },
            },
            // 切换学生
            'user.userId': { // 即使更新用户信息
                handler(newVal) {
                    this.getUserMsg()
                    if (this.param.workId != null) {
                        this.getStudentAnswer(1)
                        this.getStudentScore()
                    }
                    this.getWorkMsg()
                    if (this.param.workId != null) {
                        this.getStudentAnswer(1)
                        this.getStudentScore()
                    }
                },
            },
            // 切换作业
            'param.workId': { // 当workid发生变化的时候即使更新需要补空的数量以及分值
                handler(newVal) {
                    if (this.param.workId == null) {
                        return
                    }
                    this.getWorkMsg()
                    if (this.user.userId != null) {
                        this.getStudentAnswer(1)
                        this.getStudentScore()
                    }
                    this.getEndTime()
                },
            }
        },
        created() {
            this.getCalssList()
        },
        mounted() {
            this.waitForBothParams(() => {
                this.getStudentAnswer(1)
                this.getStudentScore()
            })
        },
        data() {
            return {
                endTime: null,
                endTimeFalt: -1,
                dialogVisible: false,
                dialogVisible_update:false,
                code: null,
                classes: null,
                param: {
                    classId: null,
                    workId: null
                },
                wakes: null,
                userIds: [],
                user: {
                    order: 0,// 记录这个userids的数组到第几个人了
                    userId: null,// 记录这个人的id
                    username: null,
                    StudentNumber: null,
                },
                workOrder: 1,
                workQuestionScore: [],// 题目分数
                workQuestionQuestion: [],// 题目信息
                workStudentScore: [],
                flat: true,//控制分数是否提交,true表示已经提交
                flat_update:true,//专门用于控制修改分数的按钮
            }
        },
        methods: {
            // 递归函数
            waitForBothParams(callback) {
                if (this.user.userId != null && this.param.workId != null) {
                    callback();
                } else {
                    setTimeout(() => {
                        this.waitForBothParams(callback);
                    }, 100);
                }
            },
            lastStudent() {
                if (this.user.order === 0) {
                    return
                } else if (this.user.order > 0) {
                    this.user.order = this.user.order - 1
                    this.user.userId = this.userIds[this.user.order]
                }
            },
            lastQuestion() {
                if (this.workOrder === 1||this.workQuestionScore.length ===0) {
                    return
                } else if (this.workOrder > 1) {
                    this.workOrder = this.workOrder - 1
                }
            },
            nextStudent() {
                if (this.user.order === this.userIds.length - 1) {
                    return;
                } else if (this.user.order >= 0) {
                    this.user.order = this.user.order + 1
                    this.user.userId = this.userIds[this.user.order]
                }
            },
            nextQuestion() {
                if (this.workOrder === this.workQuestionScore.length||this.workQuestionScore.length ===0) {
                    return
                } else if (this.workOrder > 0) {
                    this.workOrder = this.workOrder + 1
                }
            },
            // 获取班级信息
            async getCalssList() {
                const { data: res } = await this.$axios.get("/getClasses")
                this.classes = res.data
                this.param.classId = res.id
            },
            // 获取该班级需要批改的作业信息
            async getWorks() {
                const { data: res } = await this.$axios.get("/grades/getTestTwoWorks", {
                    params: {
                        classId: this.param.classId
                    }
                })
                if (res.code === 200) {
                    this.wakes = res.data
                    if (res.data.length > 0) {
                        return this.param.workId = res.data[0].id
                    }
                    return this.$message("该班级没有需要批改的作业")
                }
            },
            // 获取用户的id数组，根据学号排序
            async getUserId() {
                const { data: res } = await this.$axios.get("/grades/getUserId", {
                    params: {
                        classId: this.param.classId
                    }
                })
                this.userIds = res.data
                if (res.data.length > 0) {
                    this.user.userId = res.data[this.user.order]
                }
            },
            // 获取用户信息 ，监控：当用户id发生改变的时候 user.userId
            async getUserMsg() {
                const { data: res } = await this.$axios.get("/grades/getUserMsg", {
                    params: {
                        userId: this.user.userId
                    }
                })
                if (res.code === 200) {
                    this.user.username = res.data.username;
                    this.user.StudentNumber = res.data.studentNumber
                    return
                }
                this.$message.error("网络错误")
            },
            // 根据workId获取当前题目有多少题目以及对应的分值， 监控，当workId发生变化的时候需要更新这个 param.workId
            async getWorkMsg() {
                if (this.param.workId === null) {
                    return
                }
                const { data: res } = await this.$axios.get("/grades/getWorkMsg", {
                    params: {
                        workId: this.param.workId
                    }
                })
                if (res.code === 200) {
                    this.workQuestionScore = res.data.scores
                    this.workQuestionQuestion = res.data.question
                    this.workStudentScore = new Array(res.data.scores.length).fill(null); // 使用null填充数组
                    return
                }
                this.$message.error("网络错误")
            },

            // 根据workId和这个userId还有这个order获取到当前题目信息
            async getStudentAnswer(order) {
                if (order === 1) {// order  = 1标识是workId和这个userId发生变化,而不是order发生变化
                    this.workOrder = 1
                }
                const { data: res } = await this.$axios.get("/grades/getStudentAnswer", {
                    params: {
                        userId: this.user.userId,
                        workId: this.param.workId,
                        order: this.workOrder
                    }
                })
                if (res.code === 200) {
                    this.code = res.data
                    return
                }
                if (res.code === 201) {
                    this.code = ""
                    return this.$message("该学生未提交该题答案")
                }
                this.$message.error("网络错误")
            },

            // 教师提交学生成绩
            async submitStudentScore() {
                if (this.flat) {
                    return this.$message("该同学已经打分")
                }
                for (let i = 0; i < this.workStudentScore.length; i++) {
                    if (this.workStudentScore[i] === null) {
                        return this.$message("该学生还有题目未批改，不能进行提交")
                    }
                }
                let param = {
                    userId: this.user.userId,
                    workId: this.param.workId,
                    scores: this.workStudentScore
                }
                const { data: res } = await this.$axios.post("/grades/submitStudentScore", param)
                if (res.code === 200) {
                    this.dialogVisible = false
                    return this.$message.success("提交成功")
                } else if (res.code === 602) {
                    return this.$message.error("重复提交")
                } else {
                    return this.$message.error("网络错误")
                }
            },
            // 修改分数
            async submitStudentScore_update() {
                for (let i = 0; i < this.workStudentScore.length; i++) {
                    if (this.workStudentScore[i] === null) {
                        return this.$message("该学生还有题目未得分，不能进行提交")
                    }
                }
                let param = {
                    userId: this.user.userId,
                    workId: this.param.workId,
                    scores: this.workStudentScore
                }
                const { data: res } = await this.$axios.post("/grades/updateStudentScore", param)
                if (res.code === 200) {
                    this.dialogVisible_update = false
                    return this.$message.success("修改成功")
                } else if (res.code === 602) {
                    return this.$message.error("请走提交窗口")
                }else {
                    return this.$message.error("网络错误")
                }
            },
            // 获取学生得分数据 ：监控：user.userId param.workId
            async getStudentScore() {
                this.flat = true
                this.flat_update = true
                const { data: res } = await this.$axios.get("/grades/getStudentScore", {
                    params: {
                        userId: this.user.userId,
                        workId: this.param.workId,
                    }
                })
                if (res.code === 200) {
                    if (res.data[0] === -1) {// 表示未提交分数
                        this.flat_update = false
                        return this.flat = false
                    }
                    // 如果不等于-1，表示教师已经提交分数，直接将这个分数赋值，然后将这个设置未true，让其不能上传分数
                    this.flat = true
                    this.flat_update = true
                    this.workStudentScore = res.data
                } else {
                    return this.$message.error("网络错误")
                }
            },
            // 获取结束时间
            async getEndTime() {
                const { data: res } = await this.$axios.get("/grades/getEndTime", {
                    params: {
                        classId: this.param.classId,
                        workId: this.param.workId
                    }
                })
                if (res.code === 200) {
                    // 表示已经结束，学生不能提交答案了
                    this.endTime = res.data
                    this.endTimeFalt = 1
                }
                if (res.code === 201) {
                    // 表示还没有结束
                    this.endTime = res.msg
                    this.endTimeFalt = 0
                }
            }
        }
    }
</script>


<style lang="less" scoped>
    .first {
        margin-top: 20px;
        display: flex;
        justify-content: space-between;
    }

    .first_first {
        width: 63%;
        border: solid #000 1px;
        height: 615px;

        .question_view {
            height: 500px;
            padding-left: 10px;
            padding-right: 10px;
        }

        .change {
            border-top: 1px solid #000;
            padding: 10px 10px 0;
            display: flex;
            justify-content: space-between;
            margin-top: 30px;
            height: 30px;
        }
    }

    .first_second {
        .question_view_byOrder {
            font-size: 15px !important;
        }

        padding-top: 15px;
        padding-left: 10px;
        padding-right: 10px;
        width: 33%;
        border: solid #000 1px;
        height: 600px;

        span {
            font-size: 20px;
        }

        .el-input {
            margin-bottom: 10px;
        }
    }
</style>